/**
 * 以puppter的方式直接解析并运行json
 * @author mumulin
 * @email xinglinhe@qq.com
 * @date 2025/10
 */

import base,{
	jump,action_click,action_delay,
	action_jumpIndex,action_reStep,action_replayCheck,
	action_pageClick
} from '../../lib/base.js'

async function acceptCookies(page){
	try{
		await page.waitForSelector("#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll",{
			timeout: 500
		})
		await page.click("#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll")
	}catch(e){}
}

class dataWork {
	// 职业记录index
	workIndex = 0
    constructor() {}
	async signIn({data, step, index, page}){
		// 输入邮箱
		if (step.type === 'change' && step.selectors?.[0]?.[0] === 'aria/Email*') {
			step.value = data.account.Email
		}
		// 输入密码
		if (step.type === 'change' && step.selectors?.[0]?.[0] === 'aria/Password*') {
			step.value = data.account.Password
		}
		// 登陆之后如果已存在记录则进入记录继续编辑，否则常规创建记录
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "aria/  Start an application") {
			try{
				await base.delay(5000);
				await page.waitForSelector('div.apply-panel__intro button',{
					timeout: 30000
				})
				await page.click('div.apply-panel__intro button')
				console.log('存在application，直接进入')
				return {action:jump}
			}catch(e){
				console.log('不存在application,进入创建')
			}
		}
	}
	async addBuzzword({data, step, index, page}){
		if (index === 0 || index===1) return {action:jump} // 跳过某些步骤

	}
	async addChoice({data, step, index, page, loopIndex}){
		const choiceItem = data.choice[loopIndex]
		if (index===1) return {action:jump}
		if (step.type === 'change' && step.selectors?.[0]?.[0] === "aria/University/college name*") {
			step.value=choiceItem.collegeName
			console.log('查询赋值',choiceItem.course)
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "aria/Abertay University") {
			step.selectors=['aria/'+choiceItem.collegeName]
			console.log('赋值成功',choiceItem.collegeName)
		}
		if (step.type === 'change' && step.selectors?.[0]?.[0] === "aria/Course*") {
			step.value=choiceItem.courseSearch
			console.log('查询赋值',choiceItem.courseSearch)
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] ===  "aria/Accounting and Finance N400") {
			step.selectors=['aria/'+choiceItem.course]
			console.log('赋值成功',choiceItem.course)
		}
		if (step.type === 'waitForElement' && step.selectors?.[0]?.[0] ===  "#location option[value=\"-\"]") {
			step.selectors=[`#location option[value="${choiceItem.Location}"]`]
			console.log('等待修改成功',choiceItem.course)
		}
		if (step.type === 'change' && step.selectors?.[0]?.[0] ===  "aria/Location *") {
			step.value=choiceItem.Location
			console.log('赋值成功',choiceItem.Location)
		}
		if (step.type === 'waitForElement' && step.selectors?.[0]?.[0] ===  "#startDate option[value=\"14/09/2026\"]") {
			step.selectors=[`#startDate option[value="${choiceItem.startDate}"]`]
			console.log('等待修改成功',choiceItem.startDate)
		}
		if (step.type === 'change' && step.selectors?.[0]?.[0] ===  "aria/Start date *") {
			step.value=choiceItem.startDate
			console.log('赋值成功',choiceItem.startDate)
		}
		if (step.type === 'change' && step.selectors?.[0]?.[0] ===  "aria/Point of entry") {
			step.value=choiceItem.Point
			console.log('赋值成功',choiceItem.Point)
		}

		if (step.type === 'click' && step.selectors?.[0]?.[0] === "#liveAtHome label[for=\"liveAtHome_N\"]") {
			const sel = choiceItem.LiveAtHome=="Yes"? "#liveAtHome label[for=\"liveAtHome_Y\"]":"#liveAtHome label[for=\"liveAtHome_N\"]"
			await page.evaluate(sel => {
				$(sel).click();
			},sel);
			return {action:jump}
		}
	}
	async personalDetails({data, step, index, page}){
		if (index===1) return {action:jump}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "#personalDetails") {
			try{
				await page.waitForSelector("#personalDetails",{
					timeout: 20000
				})
				await page.evaluate(() => {
					document.querySelector("#personalDetails").click();
				});
				console.log('click','personal details');
			}catch(e){
				console.log('进入personal details 失败');
			}
			return {action:jump}
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "aria/Return to applcation overview") {
			await base.delay(5000);
		}
	}
	async nationalityDetails({data, step, index, page}){
		if (index===1) return {action:jump}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "#nationality") {
			try{
				await page.waitForSelector("#nationality",{
					timeout: 20000
				})
				await page.evaluate(() => {
					document.querySelector("#nationality").click();
				});
				console.log('click','nationality details');
			}catch(e){
				console.log('进入nationality details 失败');
			}
			return {action:jump}
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "aria/Return to applcation overview") {
			await base.delay(5000);
		}
	}
	async whereYouLive1({data, step, index, page}){
		if (index===1) return {action:jump}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "#whereYouLive") {
			try{
				await page.waitForSelector("#whereYouLive",{
					timeout: 20000
				})
				await page.evaluate(() => {
					document.querySelector("#whereYouLive").click();
				});
				console.log('click','whereYouLive details');
			}catch(e){
				console.log('进入whereYouLive details 失败');
			}
			return {action:jump}
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "aria/Return to applcation overview") {
			await base.delay(5000);
		}
	}
	async whereYouLive2({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#whereYouLive"},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async contactDetails({data, step, index, page}){
		if (index===1) return {action:jump}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "#contactDetails") {
			try{
				await page.waitForSelector("#contactDetails",{
					timeout: 20000
				})
				await page.evaluate(() => {
					document.querySelector("#contactDetails").click();
				});
				console.log('click','contactDetails details');
			}catch(e){
				console.log('进入contactDetails details 失败');
			}
			return {action:jump}
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "#hasNominatedAccess label") {
			const val = 0//0 yes 1 no
			await page.evaluate(val => {
				document.querySelectorAll('#hasNominatedAccess label')[val].click()
			},val);
			return {action:jump}
		}
		if (step.type === 'click' && step.selectors?.[0]?.[0] === "aria/Return to applcation overview") {
			await base.delay(5000);
		}
		if (step.type === 'change' && step.selectors?.[0]?.[0] === "#mobilePhoneNumber input") {
			const val = '13424007820'
			await page.evaluate(val => {
				$('#mobilePhoneNumber input').val(val)
			},val);
			console.log(step.type,step.selectors?.[0]?.[0],val);
			return {action:jump}
		}
	}
	async supportingInformation({data, step, index, page}){
		if (index===1) return {action:jump}
		// 接管support跳转
		let rs = await base.eventTrusteeship({
			data, step, index, page
		},{
			target: "#support",
			runType:action_click
		})
		if(rs) return rs
		// 返回主界面前给一点时间完成保存
		await base.eventTrusteeship({
			data, step, index, page,
		},{
			target: "aria/Return to applcation overview",
			type: 'click',
			runType: action_delay,
			delay: 5000,
		})
	}
	async moreAboutYou({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#moreAboutYou"},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async financeAndDunding({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#funding"},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async EducationGoTo({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#education"},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async EducationAddSchool({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_replayCheck, target: "education-confirmation:nth-of-type(1) button.button--primary", type: 'click', replayCheck: ()=>base.checkHasDom(page, "education-confirmation:nth-of-type(1) button.button--primary") },
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async EducationAddQualNoAction({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_delay, delay : 5000, target: "aria/Back to Education",type: 'click'},
			{runType : action_replayCheck, target: "education-confirmation:nth-of-type(1) button.button--primary", type: 'click', replayCheck: ()=>base.checkHasDom(page, "education-confirmation:nth-of-type(1) button.button--primary") },
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async EducationAddQualHasAction({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_delay, delay : 5000, target: "aria/Back to Education",type: 'click'},
			{runType : action_replayCheck, target: "education-confirmation:nth-of-type(1) button.button--primary", type: 'click', replayCheck: ()=>base.checkHasDom(page, "education-confirmation:nth-of-type(1) button.button--primary") },
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async EducationInternationalQual({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_delay, delay : 5000, target: "aria/Back to Education",type: 'click'},
			{runType : action_replayCheck, target: "education-confirmation:nth-of-type(1) button.button--primary", type: 'click', replayCheck: ()=>base.checkHasDom(page, "education-confirmation:nth-of-type(1) button.button--primary") },
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async EducationMark({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
			{runType : action_replayCheck, target: "df-modal-outlet button.button--primary", type: 'click', async replayCheck(){
				let rs = await base.checkHasDom(page, "df-modal-outlet button.button--primary")
				// if(rs) console.log('click',"df-modal-outlet button.button--primary",'数据校验未通过导致未保存成功，关闭保存提示，回到主界面');
				// else console.log('未出现保存提示，无需操作');
				return rs
			}},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	
	async goToWork({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#workExperience"}
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async workMarkAndSave({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async createWork({data, step, index, page}){
		// 可能得考虑一下createWork的这种任务得预先处理数据的
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			// {runType : action_reStep, target : "aria/Save", workIndex: this.workIndex},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async personalStatement({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#personalStatementV2"},
			{runType : action_replayCheck, target: "df-modal-outlet button.button--primary", type: 'click', replayCheck: ()=>base.checkHasDom(page, "df-modal-outlet button.button--primary") },
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async Reference({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#references"},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
			{runType : action_pageClick, target : "aria/Full title and name of referee *",type:'click', pageClick:'#recall-reference-button'},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async noReference({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#references"},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
	async ReferenceRequest({data, step, index, page}){
		const option = [
			{runType : action_jumpIndex, jumpIndex : 1},
			{runType : action_click, target : "#references"},
			{runType : action_delay, delay : 5000, target: "aria/Return to applcation overview",type: 'click'},
		]
		return await base.eventTrusteeshipAll({data, step, index, page, option})
	}
}


export default {
	// 基础运行分发
	async run(params) {
		const work =  new dataWork();
		const stepsName = params.stepsName?.trim()||null
		if(!stepsName) return
		await acceptCookies(params.page)
		if(work[stepsName]) return await work[stepsName](params);
	},
	// 步骤循环次数分发 存在则按该方法返回值执行指定次数，不存在则按steps中fieldForRunTimes字段长度执行
	// async fieldForRunTimes({data, item, stepsName}){},
	// 全程监听分发 待实现
	// listenOnStep(){}
}